package com.easyaop.core;

import net.bytebuddy.agent.ByteBuddyAgent;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.security.ProtectionDomain;
import java.util.LinkedList;
import java.util.List;

public class Inst {
    public static Instrumentation inst = ByteBuddyAgent.install();

    public static byte[] getBytes(Class<?> clazz) {
        List<byte[]> ret = new LinkedList<>();
        try {
            ClassFileTransformer transformer = new ClassFileTransformer() {
                @Override
                public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
                    if (classBeingRedefined == clazz) {
                        ret.add(classfileBuffer);
                    }
                    throw new RuntimeException();
                }
            };
            inst.addTransformer(transformer, true);
            inst.retransformClasses(clazz);
            inst.removeTransformer(transformer);
            return ret.get(0);
        } catch (UnmodifiableClassException e) {
            throw new RuntimeException(e);
        }
//        return inst.getAllLoadedClasses()[0].getClassLoader().getResourceAsStream(clazz.getName().replace(".", "/") + ".class").readAllBytes();
    }
}
